using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Text;
using System.Security.Cryptography;
namespace Home.Utils
{
    /// <summary>
    /// Class for encode and decode
    /// </summary>
    public class CypherTextUtil
    {
        public static string defaultKey = "H23z4637_37d!461*a";
        public static string MD5Encrypt(string strSource)
        {
            byte[] srcBytes = null;
            byte[] encodedByte = null;

            try
            {
                MD5 md5 = new MD5CryptoServiceProvider();
                srcBytes = ASCIIEncoding.Default.GetBytes(strSource);
                encodedByte = md5.ComputeHash(srcBytes);

            }
            catch (Exception ex)
            {
                throw ex;
            }
            return BitConverter.ToString(encodedByte).Replace("-", "").ToLower();

        }
        public static string Encrypt(string toEncrypt, string key)
        {
            byte[] keyArr;
            byte[] toEncryptArr = UTF8Encoding.UTF8.GetBytes(toEncrypt);
            try
            {
                MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
                keyArr = md5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
                md5.Clear();
                TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();

                tdes.Key = keyArr;
                tdes.Mode = CipherMode.ECB;
                tdes.Padding = PaddingMode.ISO10126;
                ICryptoTransform cTransform = tdes.CreateEncryptor();
                byte[] rsArr = cTransform.TransformFinalBlock(toEncryptArr, 0, toEncryptArr.Length);

                tdes.Clear();
                return Convert.ToBase64String(rsArr);
            }
            catch (Exception ex) { throw ex; }
        }
        public static string Decrypt(string cypherString, string key)
        {
            byte[] keyArr = null;
            byte[] encryptedArr = null;
            try
            {
                encryptedArr = Convert.FromBase64String(cypherString);
                MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();

                keyArr = md5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
                md5.Clear();

                TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();

                tdes.Key = keyArr;
                tdes.Padding = PaddingMode.ISO10126;
                tdes.Mode = CipherMode.ECB;
                ICryptoTransform cTransform = tdes.CreateDecryptor();
                byte[] resultArr = cTransform.TransformFinalBlock(encryptedArr, 0, encryptedArr.Length);
                tdes.Clear();
                return UTF8Encoding.UTF8.GetString(resultArr);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }

}